<script setup>
import PageContainer from "@/components/PageContainer/index.vue";
import { reactive, ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

import {
  getMenuListService,
  deleteMenuService,
  updateMenuStatusService,
  addOrUpdateMenuService,
} from "@/api/menu";

onMounted(() => {
  getList();
});

// 表格数据
const tableData = ref([]);
const loading = ref(false);

// 菜单参数
const menuParams = reactive({
  id: "",
  name: "",
  code: "",
  pid: 0,
  level: 0,
  type: 1,
  status: 1,
  sort_order: 0,
});

// 抽屉表单配置
const menuContent = reactive([
  {
    type: "input",
    id: "name",
    label: "菜单名称",
    rules: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],
  },
  {
    type: "input",
    id: "code",
    label: "权限标识",
    rules: [{ required: true, message: "请输入权限标识", trigger: "blur" }],
  },
  {
    type: "select",
    id: "type",
    label: "菜单类型",
    options: [
      { label: "菜单", value: 1 },
      { label: "按钮", value: 2 },
    ],
    rules: [{ required: true, message: "请选择菜单类型", trigger: "change" }],
    hidden: (row) => {
      console.log(row);
      return Boolean(row.id);
    },
  },
  {
    type: "input-number",
    id: "sort_order",
    label: "排序",
    el: {
      min: 0,
      controlsPosition: "right",
    },
  },
  {
    type: "radio-group",
    id: "status",
    label: "状态",
    options: [
      { label: "启用", value: 1 },
      { label: "禁用", value: 0 },
    ],
  },
]);

const drawer = ref(false);
const ruleFormRef = ref();

// 获取列表数据
const getList = async () => {
  loading.value = true;
  try {
    const { code, result } = await getMenuListService();
    if (code === 0) {
      tableData.value = result || [];
    }
    console.log(result);
  } catch (error) {
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 添加子菜单
const addSubMenu = (row) => {
  drawer.value = true;
  Object.assign(menuParams, {
    name: "",
    code: "",
    pid: row.id,
    level: row.level + 1,
    type: 1,
    status: 1,
    sort_order: 0,
  });
};

// 更新状态
const changeMenuStatus = async (value, row) => {
  try {
    await ElMessageBox.confirm(
      `确认${value ? "启用" : "禁用"}菜单: ${row.name}？`,
      "提示",
      {
        type: "warning",
      }
    );

    await updateMenuStatusService({
      id: row.id,
      status: Number(value),
    });

    ElMessage.success(`${value ? "启用" : "禁用"}成功`);
    getList();
  } catch (error) {
    console.error(error);
  }
};

// 删除菜单
const deleteMenu = async (row) => {
  try {
    await ElMessageBox.confirm(`确认删除菜单: ${row.name}？`, "提示", {
      type: "warning",
    });

    await deleteMenuService(row.id);
    ElMessage.success("删除成功");
    getList();
  } catch (error) {
    console.error(error);
  }
};

// 提交表单
const confirmClick = async () => {
  if (!ruleFormRef.value) return;

  try {
    await ruleFormRef.value.methods.validate();
    const res = await addOrUpdateMenuService(menuParams);

    if (res.code === 0) {
      drawer.value = false;
      ElMessage.success(menuParams.id ? "更新成功" : "添加成功");
      getList();
    }
  } catch (error) {
    console.error(error);
  }
};

// 取消
const cancelClick = () => {
  Object.assign(menuParams, {
    id: "",
    name: "",
    code: "",
    pid: 0,
    level: 0,
    type: 1,
    status: 1,
    sort_order: 0,
  });
  drawer.value = false;
};
</script>

<template>
  <div>
    <page-container title="菜单管理">
      <el-table
        :data="tableData"
        style="width: 100%"
        row-key="id"
        border
        :tree-props="{ children: 'children' }"
        v-loading="loading"
      >
        <el-table-column prop="name" label="菜单名称" />
        <el-table-column prop="code" label="权限标识" />
        <el-table-column prop="type" label="菜单类型" align="center">
          <template #default="{ row }">
            {{ { 1: "菜单", 2: "按钮" }[row.type] }}
          </template>
        </el-table-column>
        <el-table-column
          prop="sort_order"
          label="排序"
          align="center"
          width="80"
        />
        <el-table-column prop="status" label="状态" align="center" width="100">
          <template #default="{ row }">
            <el-switch
              :model-value="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="(val) => changeMenuStatus(val, row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="280">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              :disabled="row.type === 2"
              @click="addSubMenu(row)"
            >
              添加子菜单
            </el-button>
            <el-button
              type="primary"
              link
              @click="
                () => {
                  drawer = true;
                  Object.assign(menuParams, row);
                }
              "
            >
              编辑
            </el-button>
            <el-button type="danger" link @click="deleteMenu(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </page-container>

    <el-drawer v-model="drawer" @close="cancelClick">
      <template #header>
        <h4>{{ menuParams.id ? "编辑菜单" : "新增菜单" }}</h4>
      </template>
      <template #default>
        <el-form-renderer
          label-width="100px"
          :content="menuContent"
          ref="ruleFormRef"
          v-model:FormData="menuParams"
        />
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelClick">取消</el-button>
          <el-button type="primary" @click="confirmClick">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<style scoped>
.render-form :deep(.el-select) {
  width: 100%;
}
</style>
